import java.io.*;

public class BookDaoImpl implements  IBookDao{
    //请完成类的设计
    private String path;
    public BookDaoImpl(){
        path = Database.getBookPath();
    }
    public void addBook(Book b) {

        try {
            ObjectOutputStream objectOut = null;
            objectOut = new AppendingObjectOutputStream(new FileOutputStream(path,true));
            objectOut.writeObject(b);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOut != null) {
                try{
                    objectOut.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public Book getBookById(String id) {
        Book book = null;
        FileInputStream fin = null;
        ObjectInputStream ois = null;
        try {
            fin = new FileInputStream(path);
            ois = new ObjectInputStream(fin);
            while (fin.available() != 0) {
                book = (Book)ois.redObject();
                if (book.getBid().equals(id)){
                    return book;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try{
                if(ois != null) {
                    ois.close();
                }
            } catch(IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public void printBooks() {
        Book book = null;
        FileInputStream fis = null;
        ObjectInputStream ois = null;
        try {
            fis = new FileInputStream(path);
            ois = new ObjectInputStream(fis);
            while (fis.available() != 0) {
                book = (Book)ois.readObject();
                System.out.println(book);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (ois != null) {
                    ois.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}